import styles from './index.less';
import {Outlet, history, useLocation, useModel} from 'umi';
import {Tabs, App} from 'antd';
import {PageContainer, ProLayout, ProBreadcrumb} from '@ant-design/pro-components';
import {useState, useEffect} from 'react';
import {createFromIconfontCN} from '@ant-design/icons';
import Footer from './Footer';
import RightContent from './RightContent';
import Settings from '../../config/defaultSettings';

const IconFont = createFromIconfontCN({scriptUrl: '//at.alicdn.com/t/c/font_3885286_k1rrlsamjn.js'});

/* tree to array */
function treeToArray(tree) {
  let res = [];
  for (const item of tree) {
    const {routes, ...i} = item;
    if (routes && routes.length) {
      res = res.concat(treeToArray(routes));
    }
    res.push(i);
  }
  return res;
}

/* layout */
export default function Layout() {
  const [defaultPanes, setDefaultPanes] = useState([{label: '首页管理', key: '/'}]);
  const [activeKey, setActiveKey] = useState(defaultPanes[0].key);
  const [collapsed, setCollapsed] = useState(false);
  const location = useLocation();
  const [pathname, setPathname] = useState(location.pathname);

  const {initialState} = useModel('@@initialState');
  const {loginInfo} = initialState || {};
  // 侧边栏菜单
  let routes = initialState?.routes ?? [];

  /* 监听路由 */
  useEffect(() => {
    const tabArr = treeToArray(routes);
    const tabIdx = tabArr.findIndex(tab => tab.path === location.pathname);
    // 判断菜单中是否存在当前路由
    if (tabIdx >= 0 && tabArr[tabIdx].name) {
      setPathname(location.pathname || '/');
      setActiveKey(location.pathname);
      if (defaultPanes.findIndex((pane) => pane.key === location.pathname) < 0) {
        setDefaultPanes([...defaultPanes, {label: tabArr[tabIdx].name, key: location.pathname}]);
      }
    } else {
      setActiveKey(null);
    }
  }, [location]);

  /* 点击标签 */
  const onChange = (key) => {
    setActiveKey(key);
    setPathname(key);
    history.replace(key);
  };

  /* 关闭标签 */
  const onEdit = (targetKey, action) => {
    if (action === 'remove' && targetKey !== '/') {
      const targetIdx = defaultPanes.findIndex((pane) => pane.key === targetKey);
      // 删除标签
      setDefaultPanes(defaultPanes.filter((pane) => pane.key !== targetKey));
      // 关闭当前路由
      if (targetKey === location.pathname) {
        let currentPane = defaultPanes[targetIdx - 1];
        setActiveKey(currentPane.key);
        setPathname(currentPane.key);
        history.replace(currentPane.key);
      }
    }
  };

  return (
    <App>
      <ProLayout
        collapsed={collapsed}
        onCollapse={collapsed => setCollapsed(collapsed)}
        title={`${loginInfo.tenantAbbrevia ? loginInfo.tenantAbbrevia : Settings.title} - 运营管理系统`}
        className={styles.myLayout8748932}
        logo={loginInfo.tenantLogo ? loginInfo.tenantLogo : Settings.logo}
        layout={Settings.layout}
        headerContentRender={() => (
          <div style={{display: 'flex', alignItems: 'center', justifyContent: 'space-between'}}>
            <ProBreadcrumb/>
            <RightContent/>
          </div>
        )}
        breadcrumbRender={(routers) => [{path: '#', breadcrumbName: '当前位置'}, ...routers]}
        token={Settings.token}
        location={{pathname}}
        onMenuHeaderClick={() => {
          history.push('/');
        }}
        route={{routes}}
        menuItemRender={(item) => (
          <a className={styles.myMenuItem} onClick={() => {
            if (item.path) {
              history.push(item.path);
            }
          }}>
            {item.icon && <IconFont type={item.icon}/>} <span className={styles.myMenuItemSpan}>{item.name}</span>
          </a>
        )}
        subMenuItemRender={(item) => {
          return (
            <span className={'ant-pro-menu-item'}>
            <span role={'img'} className={'anticon'}>
              {item.icon && <IconFont type={item.icon}/>}
            </span>
            <span>{item.name}</span>
          </span>
          );
        }}
      >
        <PageContainer ghost style={{padding: 0}} header={{title: undefined, breadcrumb: {}}}>
          <div className={styles.mainContent} style={{width: collapsed ? 'calc(100vw - 70px)' : 'calc(100vw - 215px)'}}>
            <Tabs
              className={styles.myTabs264873} size={'small'} hideAdd
              onChange={onChange} activeKey={activeKey} type='editable-card' onEdit={onEdit} items={defaultPanes}
              tabBarStyle={{background: '#fff', margin: 0, padding: '6px', paddingRight: '12px'}}
            />
            <div style={{height: 'calc(100vh - 132px)'}}>
              <Outlet/>
            </div>
          </div>
          <Footer style={{width: collapsed ? 'calc(100vw - 60px)' : 'calc(100vw - 215px)'}}/>
        </PageContainer>
      </ProLayout>
    </App>
  );
}
